﻿using System;
using System.Collections.Generic;
using System.IO;
using Honest.MES.Contracts.Interfaces;
using Newtonsoft.Json;

namespace Honest.MES.WPF.Services
{
    public class ConfigurationService : IConfigurationService
    {
        // 注意：如果此字段声明为readonly，保持其只读特性
        private readonly Dictionary<string, object> _settings = new Dictionary<string, object>();

        public T GetSetting<T>(string key, T defaultValue = default)
        {
            if (_settings.TryGetValue(key, out object value) && value is T typedValue)
            {
                return typedValue;
            }
            return defaultValue;
        }

        public void SaveSetting<T>(string key, T value)
        {
            _settings[key] = value;
        }

        public void LoadConfiguration()
        {
            try
            {
                if (File.Exists("appsettings.json"))
                {
                    var json = File.ReadAllText("appsettings.json");
                    // 关键修改：不直接赋值给_settings，而是先清空再添加数据
                    var loadedSettings = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);

                    _settings.Clear();
                    foreach (var kvp in loadedSettings)
                    {
                        _settings[kvp.Key] = kvp.Value;
                    }
                }
            }
            catch (Exception ex)
            {
                // 建议记录错误（而非忽略），便于排查问题
                // 例如：_logger?.LogError("加载配置失败", ex);
            }
        }

        public void SaveConfiguration()
        {
            try
            {
                var json = JsonConvert.SerializeObject(_settings, Formatting.Indented);
                File.WriteAllText("appsettings.json", json);
            }
            catch (Exception ex)
            {
                // 建议记录错误
                // 例如：_logger?.LogError("保存配置失败", ex);
            }
        }
    }
}
